package com.gxks.mall_dictionary.service.impl;

import com.gxks.commons.entity.Dictionary;
import com.gxks.commons.entity.Manager;
import com.gxks.commons.entity.ResponseData;
import com.gxks.mall_dictionary.dao.DictionaryDao;
import com.gxks.mall_dictionary.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * 字典模块业务逻辑实现
 */
@Service
@Transactional
public class DictionaryServiceImpl implements DictionaryService {

    private static final String MANAGER_URL = "http://localhost:8002/";

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据主键查询字典数据
     * @param id
     * @return
     */
    @Override
    public Dictionary getDictionaryById(Long id) {
        return dictionaryDao.selectById(id);
    }

    @Override
    public List<Dictionary> getDictionaries() {
        return dictionaryDao.selectList(null);
    }

    @Override
    public List<Dictionary> getDictionaries(String dicType) {
        return dictionaryDao.selectByDictype(dicType);
    }

    @Override
    public int insert(Dictionary dictionary) {
        return dictionaryDao.insert(dictionary);
    }

    @Override
    public int update(Dictionary dictionary) {
        return dictionaryDao.updateById(dictionary);
    }

    @Transactional
    @Override
    public int deleteById(Long id) {
        //调用关联的子数据模块查询是否有数据占用了该外键，如果有，做关联数据处理
        ResponseData<List<Manager>> result =
                restTemplate.getForObject(MANAGER_URL + "manager/manager?manager_state=" + id,
                ResponseData.class);
        if(result.getData() != null && !result.getData().isEmpty()){
            restTemplate.put(MANAGER_URL + "manager/resetState" , id );
        }
        return dictionaryDao.deleteById(id);
    }

    @Override
    public int delete(List<Long> ids) {
        return dictionaryDao.deleteBatchIds(ids);
    }
}
